package efu.nf.seckilldemo.service.consumer;

import efu.nf.seckilldemo.common.config.RabbitmqConfig;
import efu.nf.seckilldemo.common.enumeration.RedisKeyEnum;
import efu.nf.seckilldemo.entity.Order;
import efu.nf.seckilldemo.mapper.GoodsMapper;
import efu.nf.seckilldemo.mapper.OrderMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author lwj
 * @create 2025-09-29-9:54
 *
 * 订单消费者
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderConsumer {
    private final OrderMapper orderMapper;
    private final GoodsMapper goodsMapper;
    private final RedisTemplate redisTemplate;

    /**
     * 监听队列
     *
     * 订单状态：
     * 0.未支付
     * 1.已支付
     * 2.已失效
     * @param orderId 订单编号
     */
    @RabbitListener(queues = RabbitmqConfig.QUEUE_KEY)
    public void consume(Integer orderId) {
        log.info("订单消费者监听到订单：{}", orderId);
        // 查询订单状态
        Order order = orderMapper.getOrderById(orderId);
        // 订单未支付
        if(order.getOrderStatus() == 0){
            log.error("{}，订单已取消",orderId);
            orderMapper.updateStatus(orderId,2);
            // 回填库存
            redisTemplate.opsForValue().increment(RedisKeyEnum.SECKILL_GOODS_STOCK_PREFIX.getPrefix()+order.getGoodsId());
        }else{
            log.info("{}，订单支付成功",orderId);
            // 商品修改库存
            goodsMapper.decrStock(order.getGoodsId());
        }
    }
}